package com.example.tongyao.utils;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.*;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 公用类
 *
 * @version 1.0
 * @author tongyao
 * @since 2020-06-13
 */
public class PubClass {

    /**
     * 获得数字随机数
     *
     * @param numberCount
     * @return
     */
    public static String getRandomNumber(int numberCount){
        String numberStr = "";
        Random ra = new Random();
        for (int i = 0;i < numberCount;i++){
            numberStr += ra.nextInt(10)+"";
        }
        return  numberStr;
    }

    /**
     * 获得字母随机数
     *
     * @param numberCount
     * @return
     */
    public static String getLetterRandomNumber(int numberCount){
        String[] number = new String[]{"0","1","2","3","4","5","6","7","8","9",
                "a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z",
                "A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
        String numberStr = "";
        Random ra = new Random();
        for (int i = 0;i < numberCount;i++){
            numberStr += number[ra.nextInt(62)];
        }
        return  numberStr;
    }

    /**
     * 获得限制数字大小的随机数
     *
     * @param numberLen
     * @return
     */
    public static int getRandomNumberSize(int numberLen){
        Random ra = new Random();
        return  ra.nextInt(numberLen);
    }

    /**
     * 获得当前系统的年月日
     *
     * @return
     */
    public static String getDate(){
        String pattern = "yyyy-MM-dd";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
        Date date = new Date();
        String dates = simpleDateFormat.format(date);
        return dates;
    }

    /**
     * 获得当前系统的当前秒数
     *
     * @return
     */
    public static String getTime(){
        String pattern = "HH:mm:ss";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
        Date date = new Date();
        String time = simpleDateFormat.format(date);
        return time;
    }

    /**
     * 获得当前系统的年月日秒数
     *
     * @return
     */
    public static Date getDateTime(){
        String pattern = "yyyy-MM-dd HH:mm:ss";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
        Date date = new Date();
        try {
            date = simpleDateFormat.parse(simpleDateFormat.format(date));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }


    /**
     * 获取今年是哪一年
     *
     * @return
     */
    public static int getNowYear() {
        Date date = new Date();
        GregorianCalendar gc = (GregorianCalendar) Calendar.getInstance();
        gc.setTime(date);
        return Integer.valueOf(gc.get(1));
    }

    /**
     * 获取本月是哪一月
     *
     * @return
     */
    public static int getNowMonth() {
        Date date = new Date();
        GregorianCalendar gc = (GregorianCalendar) Calendar.getInstance();
        gc.setTime(date);
        return gc.get(2) + 1;
    }

    /**
     * 根据当前日期获取前x天日期
     *
     * @param dayCount 前几天
     * @return
     */
    public static String getFirstxDayCount(int dayCount){
        SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd" );
        Date today = new Date();
        Calendar theCa = Calendar.getInstance();
        theCa.setTime(today);
        theCa.add(theCa.DATE, + dayCount); //最后一个数字30可改，30天的意思
        Date start = theCa.getTime();
        return sdf.format(start);
    }

    /**
     * 获取昨天的开始时间
     *
     * @return
     */
    public static String getYesterdayDate() {
        Calendar cal = new GregorianCalendar();
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);

        Calendar cal2 = new GregorianCalendar();
        cal2.setTime(cal.getTime());
        cal2.add(Calendar.DAY_OF_MONTH, -1);
        return new Timestamp(cal2.getTimeInMillis()).toString().split(" ")[0];
    }

    /**
     * 获取明天的开始时间
     *
     * @return
     */
    public static String getTomorrowDate() {
        Calendar cal = new GregorianCalendar();
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);

        Calendar cal2 = new GregorianCalendar();
        cal2.setTime(cal.getTime());
        cal2.add(Calendar.DAY_OF_MONTH, 1);
        return new Timestamp(cal2.getTimeInMillis()).toString().split(" ")[0];
    }

    /**
     * 根据开始结束日期获得中间所有天数数量
     *
     * @param starTime 开始日期
     * @param endTime   结束日期
     * @return
     */
    public static String byStartEndDateGetMiddleDay(String starTime,String endTime){
        SimpleDateFormat formatter =   new SimpleDateFormat( "yyyy-MM-dd");
        Date date1= null;
        Date date = null;
        Long l = 0L;
        try {
            date = formatter.parse(endTime);
            long ts = date.getTime();
            date1 =  formatter.parse(starTime);
            long ts1 = date1.getTime();

            l = (ts - ts1) / (1000 * 60 * 60 * 24);

        } catch (ParseException e) {
            e.printStackTrace();
        }
        return l.intValue() + "";

    }

    /**
     * 获得本周开始结束日期
     *
     * @return
     */
    public static String[] getWeekStartEndDate(){
        Calendar ca=Calendar.getInstance();
        SimpleDateFormat f=new SimpleDateFormat("yyyy-MM-dd");
        int dayOfWeek = ca.get(Calendar.DAY_OF_WEEK);
        //中国习惯：周一是一周的开始
        if (dayOfWeek==1) {
            dayOfWeek=7;

        }else{
            dayOfWeek--;

        }
        Calendar  cal=(Calendar)ca.clone();
        cal.add(Calendar.DATE,1-dayOfWeek);
        Date date1=cal.getTime();
        cal=(Calendar)ca.clone();
        cal.add(Calendar.DATE,7-dayOfWeek);
        Date date2=cal.getTime();
        String str1=f.format(date1);
        String str2=f.format(date2);
        String[] array = new String[2];
        array[0] = str1;
        array[1] = str2;
        return array;
    }

    /**
     * 获取本月的开始结束日期
     *
     * @return
     */
    public static String[] getOriginaMonthStartEndDate() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(getNowYear(), getNowMonth() - 1, 1);


        Calendar calendar3 = Calendar.getInstance();
        if(null != calendar.getTime()) calendar3.setTime(calendar.getTime());
        calendar3.set(calendar3.get(Calendar.YEAR), calendar3.get(Calendar.MONTH),calendar3.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
        calendar3.set(Calendar.MILLISECOND, 0);

        String[] array = new String[2];
        array[0] = new Timestamp(calendar3.getTimeInMillis()).toString().toString().split(" ")[0];

        Calendar calendar2 = Calendar.getInstance();
        calendar2.set(getNowYear(), getNowMonth() - 1, 1);
        int day = calendar2.getActualMaximum(5);
        calendar2.set(getNowYear(), getNowMonth() - 1, day);

        Calendar calendar4 = Calendar.getInstance();
        if(null != calendar2.getTime()) calendar4.setTime(calendar2.getTime());
        calendar4.set(calendar4.get(Calendar.YEAR), calendar4.get(Calendar.MONTH),    calendar4.get(Calendar.DAY_OF_MONTH), 23, 59, 59);
        calendar4.set(Calendar.MILLISECOND, 999);
        array[1] = new Timestamp(calendar4.getTimeInMillis()).toString().split(" ")[0];
        return array;
    }


    /**
     * 获取某月的开始结束日期
     *
     * @param date
     * @return
     */
    public static String[] getMonthStartEndDate(String date) {
        String[] dateStr = date.split("-");
        int year = Integer.parseInt(dateStr[0]);
        int month = Integer.parseInt(dateStr[1]);

        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month - 1, 1);

        String[] array = new String[2];
        array[0] = new Timestamp(calendar.getTimeInMillis()).toString();


        Calendar calendar2 = Calendar.getInstance();
        calendar2.set(year, month - 1, 1);
        int day = calendar2.getActualMaximum(5);
        calendar2.set(year, month - 1, day);
        array[1] = new Timestamp(calendar2.getTimeInMillis()).toString();
        return array;
    }

    /**
     * 获取本年的开始时间
     *
     * @return
     */
    public static String[] getYearStartEndDate() {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, getNowYear());
        // cal.set
        cal.set(Calendar.MONTH, Calendar.JANUARY);
        cal.set(Calendar.DATE, 1);

        Calendar cal2 = Calendar.getInstance();
        cal2.set(Calendar.YEAR, getNowYear());
        cal2.set(Calendar.MONTH, Calendar.DECEMBER);
        cal2.set(Calendar.DATE, 31);

        Calendar calendar3 = Calendar.getInstance();
        if(null != cal.getTime()) calendar3.setTime(cal.getTime());
        calendar3.set(calendar3.get(Calendar.YEAR), calendar3.get(Calendar.MONTH),calendar3.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
        calendar3.set(Calendar.MILLISECOND, 0);

        String[] array = new String[2];
        array[0] = new Timestamp(calendar3.getTimeInMillis()).toString().split(" ")[0];


        Calendar calendar4 = Calendar.getInstance();
        if(null != cal2.getTime()) calendar4.setTime(cal2.getTime());
        calendar4.set(calendar4.get(Calendar.YEAR), calendar4.get(Calendar.MONTH),    calendar4.get(Calendar.DAY_OF_MONTH), 23, 59, 59);
        calendar4.set(Calendar.MILLISECOND, 999);
        array[1] = new Timestamp(calendar4.getTimeInMillis()).toString().split(" ")[0];
        return array;
    }

    /**
     * 获取开始与结束时间之间的日期列表
     * @param startDate
     * @param endDate
     * @return
     */
    public static List<String> getBetweenDateList(String startDate, String endDate) throws Exception {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date startTime = simpleDateFormat.parse(startDate);
        Date endTime = simpleDateFormat.parse(endDate);
        List<String> dateList = new ArrayList<String>();
        while(startTime.compareTo(endTime) != 1) {
            dateList.add(simpleDateFormat.format(startTime));
            startTime.setTime(startTime.getTime() + 1000 * 60 * 60 * 24);
        }
        return dateList;
    }

    //根据日期取得星期几
    public static String getWeek(String time) throws Exception{
        Calendar ca = Calendar.getInstance();
        String[] str = time.split("-");
        ca.set(Integer.parseInt(str[0]),Integer.parseInt(str[1])-1,Integer.parseInt(str[2]));
        String[] weekDays = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
        int index = ca.get(Calendar.DAY_OF_WEEK)-1;
        return weekDays[index];
    }

    /**
     * 创建文本文件
     *
     * @param path
     * @param name
     * @return
     */
    public static boolean creatTxtFile(String path,String name) {
        boolean flag = false;
        try {
            File filename = new File(path+name);
            File file = new File(path);
            file.mkdirs();
            if (!filename.exists()) {
                filename.createNewFile();
                flag = true;
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        return flag;
    }

    /**
     * 修改读取txt文件
     *
     * @param path
     * @param content
     * @param type true = 拼接，false = 覆盖
     * @return
     */
    public static boolean writeTxtFile(String path,String content,boolean type) {
        // 先读取原有文件内容，然后进行写入操作
        boolean flag = false;
        String filein = content + "\r\n";
        String temp = "";

        FileInputStream fis = null;
        InputStreamReader isr = null;
        BufferedReader br = null;

        FileOutputStream fos = null;
        PrintWriter pw = null;

        try {
            // 文件路径
            File file = new File(path);
            // 将文件读入输入流
            fis = new FileInputStream(file);
            isr = new InputStreamReader(fis);
            br = new BufferedReader(isr);
            StringBuffer buf = new StringBuffer();

            if(type){
                // 保存该文件原有的内容
                for (int j = 1; (temp = br.readLine()) != null; j++) {
                    buf = buf.append(temp);
                    // System.getProperty("line.separator")
                    // 行与行之间的分隔符 相当于“\n”
                    buf = buf.append(System.getProperty("line.separator"));
                }
            }
            //正常替换
            buf.append(filein);

            fos = new FileOutputStream(file);
            pw = new PrintWriter(fos);
            pw.write(buf.toString().toCharArray());
            pw.flush();
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (pw != null) {
                pw.close();
            }
            try {
                if (fos != null) {
                    fos.close();
                }
                if (br != null) {
                    br.close();
                }
                if (isr != null) {
                    isr.close();
                }
                if (fis != null) {
                    fis.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return flag;
    }


    /**
     * 发送QQ邮箱
     *
     * @param email
     * @param emailTitle
     * @param emailValue
     */
    public static void sendEmail(String email,String emailTitle,String emailValue) {
        try {
            Properties properties = new Properties();
            properties.put("mail.transport.protocol", "smtp");// 连接协议
            properties.put("mail.smtp.host", "smtp.qq.com");// 主机名
            properties.put("mail.smtp.port", 465);// 端口号
            properties.put("mail.smtp.auth", "true");
            properties.put("mail.smtp.ssl.enable", "true");// 设置是否使用ssl安全连接 ---一般都使用
            properties.put("mail.debug", "true");// 设置是否显示debug信息 true 会在控制台显示相关信息
            Session session = Session.getInstance(properties);
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress("aixtport@qq.com"));
            message.setRecipients(Message.RecipientType.TO, new InternetAddress[]{new InternetAddress(email)});
            message.setSubject(emailTitle);
            message.setText(emailValue);

            Transport transport = session.getTransport();
            transport.connect("aixtport@qq.com", "oluecuvgzigmdfbh");// 密码为QQ邮箱开通的stmp服务后得到的客户端授权码
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送GetHttpClient请求
     *
     * @return
     */
    public static String sendGetHttpClient(String url){
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        //System.out.println("Get："+httpGet.getURI());
        CloseableHttpResponse httpResponse = null;
        String content = "";
        try {
            httpResponse = httpClient.execute(httpGet);
            HttpEntity entity =httpResponse.getEntity();
            if(entity!=null) {
                //System.out.println("响应状态："+httpResponse.getStatusLine());
                content = EntityUtils.toString(entity,"utf-8");
                //System.err.println("响应内容："+content);
                //System.out.println("内容长度："+content.length());
            }

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if(httpResponse!=null) {
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return content;
    }

    /**
     * 发送发送PostHttpClient请求
     *
     * @param url
     * @param json
     * @return
     */
    public static String sendPostHttpClient(String url,String json){
        String result = "";
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            BasicResponseHandler handler = new BasicResponseHandler();
            StringEntity entity = new StringEntity(json, "utf-8");//解决中文乱码问题
            entity.setContentEncoding("UTF-8");
            entity.setContentType("application/json");
            httpPost.setEntity(entity);
            result = httpClient.execute(httpPost, handler);
            return result;
        } catch (Exception e) {
            e.printStackTrace();

        } finally {
            try {
                httpClient.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 发送xml（报文）请求
     * @param url
     */
    public void sendXml(String url){
        System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog");
        System.setProperty("org.apache.commons.logging.simplelog.showdatetime", "true");
        System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.commons.httpclient", "stdout");

        StringBuilder sb = new StringBuilder();
        sb.append("<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/' xmlns:fres='http://www.freshpower.com.cn'>");
        sb.append("   <soapenv:Header/>");
        sb.append("   <soapenv:Body>");
        sb.append("      <fres:sendSMS>");
        sb.append("         <fres:in0>{'orgCode':'MHAPP110000','sysCode':'D7cnHmNYXVQEaR1b','data':{ 'sender':'门户APP','receiverphone':'18888888888','messagecontent':'安全监管临期提醒，您还有未巡检任务哦，请您扫码确认，逾期后不可恢复。'}}</fres:in0>");
        sb.append("      </fres:sendSMS>");
        sb.append("   </soapenv:Body>");
        sb.append("</soapenv:Envelope>");

        String xmlString = sb.toString();

        HttpClient client = new HttpClient();
        PostMethod myPost = new PostMethod(url);
        client.getParams().setSoTimeout(300*1000);
        String responseString = null;
        try{
            myPost.setRequestEntity(new StringRequestEntity(xmlString,"text/xml","utf-8"));
            int statusCode = client.executeMethod(myPost);
            if(statusCode == HttpStatus.SC_OK){
                BufferedInputStream bis = new BufferedInputStream(myPost.getResponseBodyAsStream());
                byte[] bytes = new byte[1024];
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                int count = 0;
                while((count = bis.read(bytes))!= -1){
                    bos.write(bytes, 0, count);
                }
                byte[] strByte = bos.toByteArray();
                responseString = new String(strByte,0,strByte.length,"utf-8");
                bos.close();
                bis.close();
            }
        }catch (Exception e) {
            //log.error(e.getMessage(), e);
        }
        myPost.releaseConnection();
        client.getHttpConnectionManager().closeIdleConnections(0);
        System.out.println("responseString:"+responseString);
    }


}
